import { DynamicModule, Global, Module } from '@nestjs/common'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { APP_GUARD } from '@nestjs/core'
import { JwtModule } from '@nestjs/jwt'
import { JwtAuthGuard } from 'src/config/guard/jwt-auth.guard'
import { ConfigurationKeys } from 'src/config/resources/getConfiguration'

import { TypeOrmModule } from '@nestjs/typeorm'
import { RedisModule } from './redis/redis.module'

// 跟系统有关
const libModules: DynamicModule[] = [
  JwtModule.registerAsync({
    imports: [ConfigModule],
    useFactory: (configService: ConfigService<ConfigurationKeys>) => ({
      secret: configService.get<string>('jwt.secretkey'),
    }),
    inject: [ConfigService],
  }),

  TypeOrmModule.forRootAsync({
    imports: [ConfigModule],
    useFactory: (configService: ConfigService<ConfigurationKeys>) => ({
      type: 'mysql',
      host: configService.get<string>('mysql.host'),
      port: configService.get<number>('mysql.port'),
      username: configService.get<string>('mysql.user'),
      password: configService.get<string>('mysql.password'),
      database: configService.get<string>('mysql.database'),
      autoLoadEntities: true,
      synchronize: true
    }),
    inject: [ConfigService],
  }),
]

// 自定义的服务
const customModules = [
  RedisModule
]

/**
 * 全局共享模块
 */
@Global()
@Module({
  imports: [
    ...libModules,
    ...customModules
  ],
  providers: [
    {
      provide: APP_GUARD,
      useClass: JwtAuthGuard,
    }
  ],
  exports: [...customModules, JwtModule],
})
export class SharedModule { }
